<template>
  <div :style="{height: `${windowHeight}px`}">
    <camera
      :style="{height: `${cameraHeight}px`}"
      device-position="back"
      flash="off"
      mode="normal"
      @error="errorCamera"
      @initdone="initDoneFn"
    >
      <cover-view class="controls" style="width: 100%;height: 100%;">
        <!-- 证件拍摄指引框 -->
        <cover-image
          :src="guideImgUrl"
          class="icon-w569-h828"
        />
      </cover-view>
    </camera>
    <!--:style="{paddingBottom: `${storeState.bottomSafeDis}rpx`}"-->
    <div class="footer">
      <div class="footer_menu">
        <div class="cancel" @click="backFn">取消</div>
        <div class="shutter flex_cen_cen" @tap="takePhoto">
          <div class="shutter_inner" />
        </div>
        <div class="album" @tap="chooseImageFn">
          相册
        </div>
      </div>
    </div>
    <canvas
      v-if="isShowCanvas"
      :height="canvasHeight"
      :style="'width:' + canvasWidth * 2 + 'px;height:' + canvasHeight * 2 + 'px'"
      :width="canvasWidth"
      canvas-id="myCanvas"
    />
  </div>
</template>
<script lang="ts" setup>
import { onLoad, postFileReq, Router } from '@U/common'
import { computed, ref } from 'vue'
import { Msg, MsgLoading, MsgLoadingClear } from '@C/Msg'
import { IObj } from '@/interface'

// 用户不允许使用摄像头时触发
const errorCamera = () => {
  MsgLoadingClear()
  uni.getSetting({
    success(res) {
      if (!res.authSetting['scope.camera']) {
        uni.showModal({
          title: '提示',
          content: '请开启摄像头权限，否则无法拍照',
          confirmText: '去开启',
          success(res) {
            if (res.confirm) {
              uni.openSetting({
                success(res) {
                  if (res.authSetting['scope.camera']) {
                    uni.navigateBack({
                      delta: 1,
                    })
                  } else {
                    uni.navigateBack({
                      delta: 1,
                    })
                  }
                },
              })
            } else if (res.cancel) {
              uni.navigateBack({
                delta: 1,
              })
            }
          },
        })
      }
    },
  })
}
const guideImgUrl = computed(() => {
  switch (cardType.value) {
    case 'IDPersonImg5001': return `${import.meta.env.VITE_SHOUDAO_OSS_URL}/id_card_person_guide.png`
    case 'IDFront5001': return `${import.meta.env.VITE_SHOUDAO_OSS_URL}/id_card_front_guide.png`
    case 'IDPersonImg5002': return `${import.meta.env.VITE_SHOUDAO_OSS_URL}/hk_macao_front_guide.png`
    case 'IDFront5002': return `${import.meta.env.VITE_SHOUDAO_OSS_URL}/hk_macao_back_guide.png`
    case 'IDPersonImg5003': return `${import.meta.env.VITE_SHOUDAO_OSS_URL}/taiwan_front_guide.png`
    case 'IDFront5003': return `${import.meta.env.VITE_SHOUDAO_OSS_URL}/taiwan_back_guide.png`
  }
})

const cameraContext = ref()
const canvasHeight = ref()
const canvasWidth = ref()
const isShowCanvas = ref(false)
const selectImgSuccessFn = (way: string, res: any) => {
  let tempImagePath = ''
  way === 'takePhoto' ? tempImagePath = res.tempImagePath : tempImagePath = res.tempFilePaths[0]
  uni.getFileInfo({
    filePath: tempImagePath,
    success: async (info) => {
      // 图片超出规定大小
      if (info.size >= +10 * 1024 * 1024) return uni.showToast({ icon: 'error', title: '图片最大10MB' })
      if (way === 'takePhoto') {
        isShowCanvas.value = true
        // 获取图片信息
        uni.getImageInfo({
          src: tempImagePath,
          success: async (imgRes) => {
              const ctx = uni.createCanvasContext('myCanvas')
              // 逆时针反转90度以画布0,0为中心反转
              ctx.rotate(-90 * Math.PI / 180)
              // 图片资源位置 y轴 x轴 height width
              canvasHeight.value = imgRes.width
              canvasWidth.value = imgRes.height
              ctx.drawImage(tempImagePath, -imgRes.width, 0, imgRes.width, imgRes.height)
              // false 不接着上一次绘制图案；callback 绘制完成之后再生成图片
              ctx.draw(false, () => {
                uni.canvasToTempFilePath({
                  canvasId: 'myCanvas',
                  x: 0,
                  y: 0,
                  quality: 1,
                  width: imgRes.height,
                  height: imgRes.width,
                  // 翻倍输出宽度
                  destWidth: imgRes.height * 2,
                  // 翻倍输出高度
                  destHeight: imgRes.width * 2,
                  success: async (tempRes) => {
                    await postFileReq('/api/file/upload', tempRes.tempFilePath)
                        .then(res => {
                          MsgLoading('上传中，请稍候...')
                          const { data } = res
                          const nowData = JSON.parse(data)
                          const newFile: IObj = {
                            tempImagePath: `${import.meta.env.VITE_SHOUDAO_IMG_URL }/${ nowData.data[0]}`,
                            _path: nowData.data[0],
                            IDSide: idCardSide.value,
                          }
                          Router.back(1, newFile)
                          MsgLoadingClear()
                        })
                        .catch(() => {
                          MsgLoadingClear()
                          Msg({ icon: 'error', msg: '上传失败' })
                        })
                  },
                  fail(err) {
                    uni.showToast({
                      title: `拍照失败${err}`,
                      icon: 'none',
                      duration: 1200,
                    })
                  },
                })
              })
          },
        })
      } else { // 从相册中选不做旋转
        await postFileReq('/api/file/upload', tempImagePath)
            .then(res => {
              MsgLoading('上传中，请稍候...')
              const { data } = res
              const nowData = JSON.parse(data)
              const newFile: IObj = {
                tempImagePath: `${import.meta.env.VITE_SHOUDAO_IMG_URL }/${ nowData.data[0]}`,
                _path: nowData.data[0],
                IDSide: idCardSide.value,
              }
              Router.back(1, newFile)
              MsgLoadingClear()
            })
            .catch(() => {
              MsgLoadingClear()
              Msg({ icon: 'error', msg: '上传失败' })
            })
      }
    },
  })
}
const initDoneFn = () => {
  MsgLoadingClear()
}
// 拍照
const takePhoto = () => {
  MsgLoading('上传中，请稍候...')
  cameraContext.value.takePhoto({
    quality: 'normal',
    success: (res: any) => {
      selectImgSuccessFn('takePhoto', res)
    },
    fail: () => {
      uni.showToast({
        title: '拍照失败，请检查系统是否授权',
        icon: 'none',
        duration: 1200,
      })
    },
  })
}
const backFn = () => Router.back(1)
// 从相册选取
const chooseImageFn = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['album'],
    sizeType: ['compressed'],
    success: (res) => {
      MsgLoading('上传中，请稍候')
      selectImgSuccessFn('chooseImage', res)
    },
    fail: (err) => {
      console.log(err)
    },
  })
}
const idCardSide = ref('')
const windowHeight = ref()
const cameraHeight = ref()
const cardType = ref('')
onLoad((options:any) => {
  MsgLoading()
  // windowHeight = 屏幕高度 - (状态栏 + 导航栏)
  windowHeight.value = uni.getSystemInfoSync().windowHeight
  // cameraHeight.value = uni.getSystemInfoSync().windowHeight - 110
  cameraHeight.value = uni.getSystemInfoSync().windowHeight - 135.25
  idCardSide.value = options.side
  cardType.value = options.side + options.cardType
  if (uni.createCameraContext) {
    cameraContext.value = uni.createCameraContext()
  } else {
    // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
    uni.showModal({
      title: '提示',
      content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
    })
  }
})
</script>
<style lang="less" scoped>
.controls {
  display: flex;
  align-items: center;
  justify-content: center;
  .icon-w569-h828 {
    //width: 569rpx;
    //height: 828rpx;
    width: 100vw;
    height: 100%;
  }
}
.footer {
  width: 100vw;
  //height: 110px;
  height: 135.25px;
  background-color: #000;
  .footer_menu {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;
    height: 100%;
    font-size: 36rpx;
    padding: 0 73rpx;
    .cancel, .album {
      width: 100rpx;
    }
    .shutter {
      width: 145rpx;
      height: 145rpx;
      border-radius: 50%;
      background-color: #fff;
      .shutter_inner {
        width: 125rpx;
        height: 125rpx;
        border-radius: 50%;
        border: 4rpx solid #000;
      }
    }
  }
}
</style>
